﻿using System;
using WeiboSDK;
using System.Windows;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using Alexis.WindowsPhone;
using Microsoft.Phone.Tasks;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Xna.Framework.Media;
using System.Net;

namespace Cnblogs
{
    public class GlobalFunc
    {
        public const string ImagePath = "shared.jpg";

        public static void OpenBrowser(string url)
        {
            try
            {
                WebBrowserTask task = new WebBrowserTask();
                task.Uri = new Uri(url, UriKind.Absolute);
                task.Show();
            }
            catch (Exception ex)
            {
               
            }
        }

        private static bool _isOpeningTask = false;
        public static void OpenEmail(string to, string subject, string body = "")
        {
            if (_isOpeningTask)
            {
                return;
            }
            _isOpeningTask = true;
            try
            {
                EmailComposeTask task = new EmailComposeTask();
                if (!string.IsNullOrEmpty(to))
                {
                    task.To = to;
                }
                task.Subject = subject;
                task.Body = body;
                task.Show();
            }
            catch (Exception ex)
            {
                
            }
        }

        public static void OpenSMS(string body)
        {
            if (_isOpeningTask)
            {
                return;
            }
            _isOpeningTask = true;
            try
            {
                SmsComposeTask task = new SmsComposeTask();
                task.Body = body;
                task.Show();
            }
            catch
            {
                
            }
        }

        public static void OpenReview()
        {
            if (_isOpeningTask)
            {
                return;
            }
            _isOpeningTask = true;
            try
            {
                MarketplaceReviewTask task = new MarketplaceReviewTask();
                task.Show();
            }
            catch (Exception ex)
            {
                
            }
        }

        public static void OpenApp(string productId)
        {
            try
            {
                MarketplaceDetailTask task = new MarketplaceDetailTask();
                task.ContentIdentifier = productId;
                task.ContentType = MarketplaceContentType.Applications;
                task.Show();
            }
            catch (Exception ex)
            {
                
            }
        }

        public static void LogOffWeibo()
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (store.FileExists(WeiboAPI.API_Weibo_User_File))
                {
                    store.DeleteFile(WeiboAPI.API_Weibo_User_File);
                }
                if (store.FileExists(WeiboAPI.API_Access_Token))
                {
                    store.DeleteFile(WeiboAPI.API_Access_Token);
                }
                App.Token = null;
                App.weiboUser = null;
            }
        }

        private static bool _isDarkTheme;
        public static bool IsDarkTheme
        {
            get
            {
                return _isDarkTheme;
            }
            set
            {
                _isDarkTheme = value;
                PersistHelper.SaveSettingToStorage(Constants.S_IsDarkTheme, value);
            }
        }

        private static bool _IsEnableImage;
        public static bool IsEnableImage
        {
            get
            {
                return _IsEnableImage;
            }
            set
            {
                _IsEnableImage = value;
                PersistHelper.SaveSettingToStorage(Constants.S_IsEnableImage, value);
            }
        }

        #region 刷新条数
        private static int _pageSize;
        public static int PageSize
        {
            get
            {
                return _pageSize;
            }
            set
            {
                _pageSize = value;
                PersistHelper.SaveSettingToStorage(Constants.S_PageCount, value);
            }
        }
        #endregion

        public static void SaveImage(BitmapImage orgSource, string fileName)
        {
            MemoryStream source = new MemoryStream();
            try
            {
                MediaLibrary library = new MediaLibrary();
                WriteableBitmap bitmap = new WriteableBitmap(orgSource);
                Extensions.SaveJpeg(bitmap, source, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
                source.Seek(0, SeekOrigin.Begin);
                source.Seek(0, SeekOrigin.Current);
                library.SavePicture(fileName, source);
                source.Close();
                MessageBox.Show("保存图片成功");
            }
            catch
            {
                MessageBox.Show("保存图片失败");
            }
            finally
            {
                source.Close();
            }

        }

        public static void DownloadImage(string imgUrl)
        {
            WebClient client = new WebClient();
            client.OpenReadAsync(new Uri(imgUrl, UriKind.Absolute));
            client.OpenReadCompleted += (e1, e2) =>
                {
                    using (var isostore = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (var stream = isostore.OpenFile(GetParsePath(imgUrl), FileMode.Create, FileAccess.Write))
                        {
                            e2.Result.CopyTo(stream);
                        }
                    }
                };
        }

        public static string GetParsePath(string url)
        {
            return url.Replace("://", "").Replace("/", "_").Replace("?", "_").Replace("&", "_");
        }

        public static string getShareImagePath()
        {
            string path = "";

            if (!string.IsNullOrEmpty(App.ShareImagePath))
            {
                path = GetParsePath(App.ShareImagePath);
            }
            else
            {
                path = "cnblogs_logo.jpg";
                if (!IsFileExists("cnblogs_logo.jpg"))
                {
                    var stream = App.GetResourceStream(new Uri("Cnblogs;component/Images/cnblogs_logo.jpg", UriKind.Relative)).Stream;
                    try
                    {
                        using (var isostore = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            using (var stream2 = isostore.OpenFile(path, FileMode.Create, FileAccess.Write))
                            {
                                stream.CopyTo(stream2);
                                stream.Close();
                            }
                        }
                    }
                    catch (Exception)
                    {

                        throw;
                    }
                    finally
                    {
                        stream.Close();
                    }
                }
            }

            return path;
        }

        public static bool IsFileExists(string fileName)
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                return store.FileExists(fileName) ? true : false;
            }
        }
    }
}
